package org.lds.scheduled.job.sample.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.lds.scheduled.job.common.exception.BusinessException;
import org.lds.scheduled.job.common.exception.ExceptionMessage;
import org.lds.scheduled.job.common.model.dto.ResultDTO;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * 全局异常处理
 *
 * @author lidongsheng 2021/3/16 20:03
 * @version V1.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 兜底
     *
     * @param e
     */
    @ExceptionHandler(Throwable.class)
    public ResultDTO handleThrowable(Throwable e) {
        log.error("handleThrowable", e);
        return ResultDTO.fail("system.error", "系统错误");
    }

    /**
     * 自定义业务异常
     *
     * @param e
     */
    @ExceptionHandler(BusinessException.class)
    public ResultDTO handleBusinessException(BusinessException e) {
        ExceptionMessage exceptionMessage = e.getExceptionMessage();
        return ResultDTO.fail(exceptionMessage.getCode(), exceptionMessage.getMessage());
    }

    /**
     * controller层
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResultDTO handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return ResultDTO.fail("invalid.param", e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * controller层
     */
    @ExceptionHandler({BindException.class})
    public ResultDTO handleBindException(BindException e) {
        return ResultDTO.fail("invalid.param", e.getFieldError().getDefaultMessage());
    }

    /**
     * 支持service层校验
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public ResultDTO ConstraintViolationExceptionHandler(ConstraintViolationException e) {
        for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) {
            return ResultDTO.fail("invalid.param", constraintViolation.getMessage());
        }
        return ResultDTO.fail("invalid.param", "参数不合法");
    }

}
